package org.xtext.runtime.teleoreactive;

import java.util.HashMap;

import org.xtext.runtime.eis.EISService;
import org.xtext.runtime.interpreter.Agent;
import org.xtext.runtime.term.ITerm;
import org.xtext.runtime.term.Variable;
import org.xtext.runtime.util.Bindings;
import eis.exceptions.ManagementException;
import eis.iilang.Parameter;

public class TREISSetup implements ITRAction  {
	private ITerm id, jar;
	private EISService service;
	
	public TREISSetup(ITerm id, ITerm jar) {
		this.id = id;
		this.jar = jar;
	}
	
	public TREISSetup(ITerm id) {
		this.id = id;
	}
	
	@Override
	public TREISSetup apply(Bindings set) {
		return new TREISSetup(id.apply(set), (jar == null) ? null : jar.apply(set));
	}

	@Override
	public boolean handle(Agent agent) {
		if (jar == null) {
			agent.eisService(EISService.getService((String) Variable.rawValue(id).value()));
		} else {
			service = EISService.getService((String) Variable.rawValue(id).value(), (String) Variable.rawValue(jar).value());
			
			if (service.getEnvironmentState().equals("initializing")) {
				try {
					service.eisInit(new HashMap<String, Parameter>());
					agent.eisService(service);
				} catch (ManagementException e) {
					e.printStackTrace();
					agent.logAction(toString() + " [FAILED TO LAUNCH JAR]");
					return false;
				}
			}
		}
		agent.logAction(toString() + " [SUCCESS]");
		return true;
	}

	@Override
	public String toString() {
		String output = "eis_setup(" + id;
		if (jar != null) output += "," + jar;
		return output + ")";
	}
	
	@Override
	public TREISSetup copy() {
		return new TREISSetup(id.copy(), jar.copy());
	}
}
